<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="rules" size="large">
    <el-form-item prop="email">
      <el-input v-model="loginForm.email" placeholder="用户名： admin">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password" style="margin-bottom: 0">
      <el-row gutter="10">
        <el-col :span="16">
          <el-input v-model="loginForm.password" placeholder="验证码">
            <template #prefix>
              <el-icon class="el-input__icon">
                <lock />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button :disabled="isSendingCaptcha" @click="sendCaptcha">
            {{ isSendingCaptcha ? `重新发送(${countdown})` : '发送验证码' }}
          </el-button>
        </el-col>
      </el-row>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button icon="CircleClose" round size="large" @click="resetForm"> 重置 </el-button>
    <el-button
        icon="UserFilled"
        round
        size="large"
        type="primary"
        :loading="loading"
        @click="login"
    >
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import {User, Lock} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElNotification, FormInstance} from 'element-plus'
import type {
  LoginParams,
  LoginResponseData
} from '@/api/login/type.ts'
import {reqLogin,reqCaptchaCode} from "@/api/login";

// 引入获取当前时间的函数
import {getTime} from '@/utils/time'
// 引入用户相关的小仓库
import {useUserStore} from '@/store/modules/user.ts'

const useStore = useUserStore()
// 获取路由器
const router = useRouter()
// 获取路由对象
const route = useRoute()
// 定义变量控制按钮加载效果
let loading = ref(false)

// 表单对象的ref
const loginForms = ref<FormInstance>()

// 收集账号与密码的数据
let loginForm = reactive({
  email: '1323969797@qq.com',
  password: '',
})

// 自定义校验规则对象
const validatorUserName = (rule: any, value: string, callback: any) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('账户长度至少5个字符'))
  }
}

const validatorPassword = (rule: any, value: string, callback: any) => {
  if (value.length >= 6) {
    callback()
  } else {
    callback(new Error('密码长度至少6个字符'))
  }
}

// 表单校验的需要配置的东西
const rules = {
  email: [
    {validator: validatorUserName, trigger: 'change'},
  ],
  password: [
    {validator: validatorPassword, trigger: 'change'},
  ],
}

// 发送验证码相关
let isSendingCaptcha = ref(false)
let countdown = ref(0)

const startCountdown = () => {
  countdown.value = 60
  isSendingCaptcha.value = true
  const interval = setInterval(() => {
    countdown.value -= 1
    if (countdown.value <= 0) {
      clearInterval(interval)
      isSendingCaptcha.value = false
    }
  }, 1000)
}

const sendCaptcha = async () => {
  // 验证用户名是否填写
  await loginForms.value?.validateField('email')
  // 发送验证码请求
  const loginResponseData:LoginResponseData = await reqCaptchaCode(loginForm.email);
  if (loginResponseData.code === 200) {
    // 发送成功，请先往邮箱查看
    ElMessage({
      message: '请先往邮箱查看验证码',
      type: 'success',
    })
    // 开始倒计时
    startCountdown()
  }
}

// 重置表单
const resetForm = () => {
  loginForms.value?.resetFields()
}

// 登录按钮回调
const login = async () => {
  // 保证全部表单校验通过再发请求
  await loginForms.value?.validate()

  // 按钮加载效果
  loading.value = true
  try {
    // 保证登录成功
    await useStore.userLogin(loginForm)
    let redirect = (route.query as any).redirect
    router.push({path: redirect || '/'})
    ElNotification({
      title: `HI,${getTime()}`,
      message: '欢迎登录成功',
      type: 'success',
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      title: '登录失败',
      message: (error as Error).message,
      type: 'error',
    })
  }
}
</script>

<style scoped lang="scss">
@import '../index.scss';
</style>
